import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useLoginStore } from '@/store/modules/login'
import localCache from '@/utils/cache'
import { firstMenu } from '@/utils/mapMenus'
// 写入基本的通用路由组件
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('@/views/main/main.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('@/views/not-found/not-found.vue')
  }
]

// 创建整个路由对象
const router = createRouter({
  history: createWebHashHistory(),
  routes
})
// 定义变量是否已经动态添加过，如果刷新后load永远为0
let load = 0
router.beforeEach((to) => {
  // 获取菜单
  const menuTree = useLoginStore().userMenus
  if (to.path !== '/login') {
    const token = localCache.getCache('token')
    if (!token) {
      return '/login' // return 代替了 next()函数
    }
  }
  // 获取动态路由后刷新失效的解决办法
  if (load === 0 && menuTree.length && to.name !== 'login') {
    load++
    useLoginStore().setUserMenus(menuTree)
    return { path: to.fullPath }
  }
  // 如果要到根目录的话，就再次重定向到第一个菜单 注意写的位置顺序
  if (to.path === '/main') {
    return firstMenu.url
  }
})
export default router
